# -*- coding: utf-8 -*-
# coding:utf-8

import wejudge.kernel.general as kernel
import wejudge.apps.contest.models as ContestModel
import wejudge.apps.account.models as AccountModel
import wejudge.kernel.problem as ProblemKernel
import wejudge.apps.problem.models as ProblemModel
import ContestProvider as CP
import json
import os
import time
import datetime
import uuid
import xlrd
import zipfile

__author__ = 'lancelrq'


class ContestManager(CP.ContestProvider):

    def __init__(self, request):
        CP.ContestProvider.__init__(self, request)
        self._navbar_action = 'contest'

    def mgr_contest_setting(self, contest_id):
        """
        比赛服设置
        :param contest_id:
        :return:
        """
        if not self._check_login():
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists()
            return

        if self._user_session.user_id != contest.author.id:
            self._send_error_contest_permission_denied()
            return


        is_referee = self._check_admin_permission(contest)

        self._template_file = "contest/manager/setting.html"
        self._context = {
            'contest': contest,
            "is_referee": is_referee,
            "faq_counter": self._get_faq_counter(contest, is_referee),
            'type': 'setting',
            'cc_ignore_problem': [problem.id for problem in contest.cross_check_ignore_problem.all()],
            'problem_list': [cproblem.problem for cproblem in contest.problemset.all()]
        }

    def mgr_save_contest_setting(self, contest_id):
        """
        保存比赛设置
        :param contest_id:

        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        desconly = True if self._request.GET.get('desconly', '0') == '1' else False

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != contest.author.id:
            self._result = kernel.RESTStruct(False, "只有比赛发起者才能够执行该操作")
            return

        if desconly:
            description = self._request.POST.get("description", "")
            contest.description = description

        else:
            title = self._request.POST.get("title", "")
            if title.strip() == '':
                self._result = kernel.RESTStruct(False, "请输入比赛标题")
                return

            pause = True if self._request.POST.get("pause_judge", "0") == '1' else False
            allow_all_user = True if self._request.POST.get("allow_all_user", "0") == '1' else False
            cross_check = True if self._request.POST.get("cross_check", "0") == '1' else False
            cross_check_ratio = self._request.POST.get('cross_check_ratio', '0.8')
            ignore_problems = self._request.POST.getlist("cc_ignore_problem")
            try:
                cross_check_ratio = float(cross_check_ratio)
            except:
                cross_check_ratio = 0.8
            if cross_check_ratio < 0 or cross_check_ratio > 1:
                cross_check_ratio = 0.8

            lang = self._request.POST.getlist("lang", "")
            if len(lang) == 0:
                self._result = kernel.RESTStruct(False, "请至少分配一种评测语言")
                return
            cnt = 0
            asgn_lang = kernel.const.LANGUAGE_PROVIDE
            for i in lang:
                if i in asgn_lang:
                    cnt += 1
            if cnt == len(asgn_lang):
                lang = 'all'
            else:
                lang = ','.join(lang)

            try:
                start_time = time.mktime(datetime.datetime.strptime(self._request.POST.get("start_time"), "%Y-%m-%d %H:%M:%S").timetuple())
                end_time = time.mktime(datetime.datetime.strptime(self._request.POST.get("end_time"), "%Y-%m-%d %H:%M:%S").timetuple())
            except:
                self._result = kernel.RESTStruct(False, "时间格式错误")
                return
            try:
                for problem in contest.cross_check_ignore_problem.all():
                    if unicode(problem.id) not in ignore_problems:
                        contest.cross_check_ignore_problem.remove(problem)
                    else:
                        ignore_problems.remove(unicode(problem.id))
                for pid in ignore_problems:
                    p = ProblemModel.Problem.objects.filter(id=int(pid))
                    if p.exists():
                        contest.cross_check_ignore_problem.add(p[0])
            except:
                self._result = kernel.RESTStruct(False, "数据错误")
                return

            contest.title = title
            contest.pause = pause
            contest.allow_all_user = allow_all_user
            contest.lang = lang
            contest.cross_check = cross_check
            contest.cross_check_ratio = cross_check_ratio
            contest.start_time = start_time
            contest.end_time = end_time
            pass

        contest.save()

        self._result = kernel.RESTStruct(True)

    def mgr_user(self, contest_id):
        """
        比赛专用用户设置（ACM账号专用）
        :param contest_id:
        :return:
        """
        if not self._check_login():
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists()
            return

        if self._user_session.user_id != contest.author.id:
            self._send_error_contest_permission_denied()
            return

        if self._user_session.user_id == 'acm':
            users = AccountModel.User.objects.filter(id__startswith='team').order_by("create_time")
        else:
            users = []

        is_referee = self._check_admin_permission(contest)

        self._template_file = "contest/manager/user_mgr.html"
        self._context = {
            'users': users,
            'contest': contest,
            "is_referee": is_referee,
            "faq_counter": self._get_faq_counter(contest, is_referee),
            'type': 'user_mgr'
        }

    def mgr_participants(self, contest_id):
        """
        比赛参赛者名单（或者排除名单）
        :param contest_id:
        :return:
        """
        if not self._check_login():
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists()
            return

        if self._user_session.user_id != contest.author.id:
            self._send_error_contest_permission_denied()
            return

        is_referee = self._check_admin_permission(contest)

        self._template_file = "contest/manager/participants_mgr.html"
        self._context = {
            'participants': contest.participants.all(),
            'contest': contest,
            "is_referee": is_referee,
            "faq_counter": self._get_faq_counter(contest, is_referee),
            'type': 'participants_mgr'
        }

    def mgr_send_balloon(self, contest_id):
        if not self._check_login():
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists()
            return

        if self._user_session.user_id != contest.author.id:
            self._send_error_contest_permission_denied()
            return

        is_referee = self._check_admin_permission(contest)

        judgestatus = contest.judge_status.filter(flag=0).order_by('-id')

        # 获取题目数据
        cproblem_list = contest.problemset.order_by("index")
        # 题目索引参照表
        cpindex_list = {}
        for cproblem in cproblem_list:
            cpindex_list[cproblem.problem.id] = cproblem.index

        self._template_file = "contest/manager/send_balloon.html"
        self._context = {
            'contest': contest,
            "is_referee": is_referee,
            "judgestatus": judgestatus,
            "cpindex_list": cpindex_list
        }

    def mgr_find_participants(self, contest_id):
        """
        按照正则表达式检测用户
        :param contest:
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != contest.author.id:
            self._result = kernel.RESTStruct(False, "只有管理员才能够执行该操作")
            return

        user_reg = self._request.POST.get('user_reg', '')
        if user_reg.strip() == '':
            self._result = kernel.RESTStruct(False, "请输入要搜索的用户名或正则表达式")
            return
        try:
            users = AccountModel.User.objects.filter(id__iregex=user_reg)
            users_view = [
            {
                "id": user.id,
                "nickname": "" if user.nickname is None else user.nickname,
                "realname": "" if user.realname is None else user.realname
            } for user in users]
        except Exception:
            self._result = kernel.RESTStruct(False, "正则表达式错误")
            return

        self._result = kernel.RESTStruct(True, data=users_view)

    def mgr_add_participants(self, contest_id):
        """
        添加参赛者
        :param contest:
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != contest.author.id:
            self._result = kernel.RESTStruct(False, "只有管理员才能够执行该操作")
            return

        user_ids = self._request.POST.getlist('user_id')
        users = AccountModel.User.objects.filter(id__in=user_ids)
        for user in users:
            if not contest.participants.filter(id=user.id).exists():
                contest.participants.add(user)

        self._result = kernel.RESTStruct(True)

    def mgr_remove_participants(self, contest_id):
        """
        删除参赛者
        :param contest:
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != contest.author.id:
            self._result = kernel.RESTStruct(False, "只有管理员才能够执行该操作")
            return

        user_ids = self._request.POST.getlist('user_id')
        users = contest.participants.filter(id__in=user_ids)
        for user in users:
            contest.participants.remove(user)

        self._result = kernel.RESTStruct(True)

    def mgr_referees(self, contest_id):
        """
        裁判名单管理
        :param contest_id:
        :return:
        """
        if not self._check_login():
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists()
            return

        if self._user_session.user_id != contest.author.id:
            self._send_error_contest_permission_denied()
            return

        is_referee = self._check_admin_permission(contest)

        self._template_file = "contest/manager/referees_mgr.html"
        self._context = {
            'referees': contest.referees.all(),
            'contest': contest,
            "is_referee": is_referee,
            "faq_counter": self._get_faq_counter(contest, is_referee),
            'type': 'referees_mgr'
        }

    def mgr_add_referees(self, contest_id):
        """
        添加裁判
        :param contest:
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != contest.author.id:
            self._result = kernel.RESTStruct(False, "只有管理员才能够执行该操作")
            return

        user_ids = self._request.POST.getlist('user_id')
        users = AccountModel.User.objects.filter(id__in=user_ids)
        for user in users:
            if not contest.referees.filter(id=user.id).exists():
                contest.referees.add(user)

        self._result = kernel.RESTStruct(True)

    def mgr_remove_referees(self, contest_id):
        """
        删除裁判
        :param contest:
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != contest.author.id:
            self._result = kernel.RESTStruct(False, "只有管理员才能够执行该操作")
            return

        user_ids = self._request.POST.getlist('user_id')
        users = contest.referees.filter(id__in=user_ids)
        for user in users:
            contest.referees.remove(user)

        self._result = kernel.RESTStruct(True)

    def mgr_code_analyzer(self, contest_id, page=1, limit=100):
        """
        代码查重列表
        :param contest_id:
        :return:
        """
        if not self._check_login():
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists()
            return

        tflag, dsc = self._check_time_passed(contest)
        if tflag < 1:
            if not self._check_admin_permission(contest):
                self._send_error_contest_permission_denied()
                return

        if tflag < 1:
            ca_list = ContestModel.ContestCodeAnalysis.objects.filter(contest=contest).order_by('-levenshtein_similarity_ratio')
        else:
            ca_list = ContestModel.ContestCodeAnalysis.objects.filter(contest=contest, levenshtein_similarity_ratio__gte=0.9).order_by('-levenshtein_similarity_ratio')
        count = ca_list.count()
        pager = kernel.PagerProvider(count, limit, page, 'contest_mgr_code_analyzer', 11, self._request.GET, contest.id)
        if count > 0:
            ca_list = ca_list.all()[pager.start_idx: pager.start_idx + limit]
        else:
            ca_list = []

        is_referee = self._check_admin_permission(contest)

        self._template_file = "contest/manager/code_analyzer.html"
        self._context = {
            'list': ca_list,
            'contest': contest,
            "is_referee": is_referee,
            "faq_counter": self._get_faq_counter(contest, is_referee),
            'type': 'code_analyzer',
            'pager': pager.render()
        }

    def mgr_code_compare(self, contest_id, ca_id):
        """
        代码查重列表
        :param contest_id:
        :return:
        """
        if not self._check_login():
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists()
            return
        tflag, dsc = self._check_time_passed(contest)
        if tflag < 1:
            if not self._check_admin_permission(contest):
                self._send_error_contest_permission_denied()
                return

        ca = ContestModel.ContestCodeAnalysis.objects.filter(contest=contest, id=ca_id)
        if not ca.exists():
            self._context = '没有找到指定的代码分析结果记录'
            self._action = kernel.const.VIEW_ACTION_DEFAULT
            return
        ca = ca[0]

        ls = kernel.LocalStorage(kernel.const.USER_UPLOADCODE_DIR, '')
        code1 = ls.read_file(ca.status1.code_path)
        code2 = ls.read_file(ca.status2.code_path)

        self._template_file = "contest/manager/code_compare.html"
        self._context = {
            'code_analysis': ca,
            'code1': code1,
            'code2': code2
        }

    def mgr_set_problem_order(self, contest_id):
        # 设置题目顺序接口
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != contest.author.id:
            self._result = kernel.RESTStruct(False, "只有管理员才能够执行该操作")
            return

        data = self._request.POST.get('data', '[]')
        try:
            data = json.loads(data)
        except:
            data = []

        if len(data) < 1:
            self._result = kernel.RESTStruct(False, msg="数据错误")
            return

        index = 1
        for i in range(1, len(data)):
            cproblem = contest.problemset.filter(id=data[i])
            if not cproblem.exists():
                continue
            cproblem = cproblem[0]
            cproblem.index = index
            index += 1
            cproblem.save()

        self._result = kernel.RESTStruct(True)

    def mgr_add_new_problems(self, contest_id):
        """
        添加题目（按照题号）
        :param contest:
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != contest.author.id:
            self._result = kernel.RESTStruct(False, "只有管理员才能够执行该操作")
            return

        problem_ids = self._request.POST.get('problem_ids', '')
        problem_ids = problem_ids.split(',')
        msg = []
        for id in problem_ids:
            if contest.problemset.filter(problem__id=id).exists():
                msg.append(id + "[存在]")
                continue
            problem = ProblemModel.Problem.objects.filter(id=id)
            if not problem.exists():
                msg.append(id + "[未找到]")
                continue
            cproblem = ContestModel.ContestProblems()
            cproblem.problem = problem[0]
            cproblem.save()
            contest.problemset.add(cproblem)

        cproblems = contest.problemset.order_by("-index").order_by('id').all()
        index = 1
        for cp in cproblems:
            cp.index = index
            index += 1
            cp.save()

        if len(msg) == 0:
            self._result = kernel.RESTStruct(True, '操作成功完成')
        else:
            self._result = kernel.RESTStruct(True, '操作成功完成，但以下项目出现问题：<br />' + '<br />'.join(msg))

    def mgr_remove_problems(self, contest_id):
        """
        移除题目
        :param contest_id:
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != contest.author.id:
            self._result = kernel.RESTStruct(False, "只有管理员才能够执行该操作")
            return

        problem_ids = self._request.POST.getlist('problem_ids')
        msg = []
        for id in problem_ids:
            cproblem = contest.problemset.filter(id=id)
            if not cproblem.exists():
                msg.append(id + "[不存在]")
            else:
                cproblem = cproblem[0]
                contest.problemset.remove(cproblem)
                cproblem.delete()
                msg.append(id + "(%s)" % cproblem.index + "[移除成功]")

        cproblems = contest.problemset.order_by("-index").order_by('id').all()
        index = 1
        for cp in cproblems:
            cp.index = index
            index += 1
            cp.save()

        self._result = kernel.RESTStruct(True, '操作成功完成<br />' + '<br />'.join(msg))

    def mgr_modify_problem_setting(self, contest_id, problem_id):
        """
        题目设置
        :param contest_id:
        :param problem_id:
        :return:
        """

        if not self._check_login(True, True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._action = kernel.const.VIEW_ACTION_DEFAULT
            return

        if not self._check_permission(contest):
            self._action = kernel.const.VIEW_ACTION_DEFAULT
            return

        if self._user_session.user_id != contest.author.id:
            self._action = kernel.const.VIEW_ACTION_DEFAULT
            self._context = "只有比赛发起者才能够执行该操作"
            return

        cproblem = contest.problemset.filter(problem__id=problem_id)
        if not cproblem.exists():
            self._action = kernel.const.VIEW_ACTION_DEFAULT
            return

        self._template_file = "contest/manager/ajax_problem_setting.html"
        self._context = {
            "cproblem": cproblem[0],
            "contest": contest
        }

    def mgr_save_problem_setting(self, contest_id, problem_id):
        """
        保存题目设置
        :param contest_id:
        :param problem_id:
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != contest.author.id:
            self._result = kernel.RESTStruct(False, "只有比赛发起者才能够执行该操作")
            return

        cproblem = contest.problemset.filter(problem__id=problem_id)
        if not cproblem.exists():
            self._send_error_contest_problem_not_found(True)
            return
        cproblem = cproblem[0]

        judge_style = self._request.POST.get("judge_style", "0")
        if not str.isdigit(str(judge_style)):
            judge_style = 0
        judge_style = int(judge_style)

        lang = self._request.POST.getlist("lang")
        if len(lang) == 0:
            self._result = kernel.RESTStruct(False, "请至少分配一种评测语言")
            return
        cnt = 0
        clang = contest.lang.split(",") if contest.lang != 'all' else kernel.const.LANGUAGE_PROVIDE
        for i in lang:
            if i not in clang:
                cnt += 1
        if cnt == 0 and (len(lang) == len(clang)):
            lang = 'inherit'
        else:
            lang = ','.join(lang)

        cproblem.judge_style = judge_style
        cproblem.lang = lang
        cproblem.save()

        self._result = kernel.RESTStruct(True)

    def mgr_start_problem_rejudge(self, contest_id, problem_id):
        """
        启动重判队列
        :param contest_id:
        :param problem_id:
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != contest.author.id:
            self._result = kernel.RESTStruct(False, "只有比赛发起者才能够执行该操作")
            return

        cproblem = contest.problemset.filter(problem__id=problem_id)
        if not cproblem.exists():
            self._send_error_contest_problem_not_found(True)
            return
        cproblem = cproblem[0]

        cstatus = contest.judge_status.filter(problem=cproblem.problem)
        for status in cstatus:
            status.flag = 9
            status.save()
            jq = ProblemModel.JudgeQueue()
            jq.judge_status = status
            jq.queue_status = -1
            jq.save()

        self._result = kernel.RESTStruct(True)

    def mgr_change_status(self, contest_id, status_id):
        """
        更改评测状态
        :param contest_id:
        :param status_id:
        :return:
        """
        if not self._check_login(True, True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._action = kernel.const.VIEW_ACTION_DEFAULT
            return

        if not self._check_permission(contest):
            self._action = kernel.const.VIEW_ACTION_DEFAULT
            return

        cstatus = contest.judge_status.filter(id=status_id)
        if not cstatus.exists():
            self._action = kernel.const.VIEW_ACTION_DEFAULT
            self._context = "[Not Found]"
            return
        cstatus = cstatus[0]

        cproblem = contest.problemset.filter(problem=cstatus.problem)
        if not cproblem.exists():
            self._action = kernel.const.VIEW_ACTION_DEFAULT
            self._context = "[Not Found]"
            return
        cproblem = cproblem[0]

        if cproblem.judge_style not in [1, 2]:
            self._action = kernel.const.VIEW_ACTION_DEFAULT
            self._context = "由于当前题目设置为【自动评测】，不能使用此功能"
            return

        self._template_file = "contest/manager/change_status.html"
        self._context = {
            "status": cstatus,
            "contest": contest
        }

    def mgr_save_status_change(self, contest_id, status_id):
        """
        保存题目设置
        :param contest_id:
        :param problem_id:
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        cstatus = contest.judge_status.filter(id=status_id)
        if not cstatus.exists():
            self._result = kernel.RESTStruct(False, '没有找到相关评测记录')
            return
        cstatus = cstatus[0]

        cproblem = contest.problemset.filter(problem=cstatus.problem)
        if not cproblem.exists():
            self._send_error_contest_problem_not_found(True)
            return
        cproblem = cproblem[0]

        if cproblem.judge_style not in [1, 2]:
            self._result = kernel.RESTStruct(False, '由于当前题目设置为【自动评测】，不能使用此功能')
            return

        flag = self._request.POST.get('flag', -1)

        try:
            flag = int(flag)
        except:
            flag = -1

        if flag < 0 or flag > 8:
            self._result = kernel.RESTStruct(False, '参数错误')
            return

        cstatus.flag = flag
        cstatus.save()
        jsapi = ProblemKernel.JudgeServiceAPI(self._request)
        jsapi.status_callback_proc(cstatus)
        self._result = kernel.RESTStruct(True)

    def read_xls_to_change_team_user_info(self, contest_id):
        """
        比赛专用账号信息导入
        :param contest_id:
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != 'acm':
            self._result = kernel.RESTStruct(False, "只有ACM协会专用账号才能够执行该操作")
            return

        files = self._request.FILES.get('upload_xls')
        if files is None:
            self._result = kernel.RESTStruct(False, "没有找到上传的文件")
            return

        path = "contest_xls/%s%s" % (uuid.uuid4(), '.xls')
        file_name = os.path.join(kernel.const.IMPORT_PROCESS_TEMP_DIR, path)
        destination = open(file_name, 'wb+')
        for chunk in files.chunks():
            destination.write(chunk)
        destination.close()
        try:
            xls_sheet = xlrd.open_workbook(file_name)
            xls_table = xls_sheet.sheet_by_index(0)
            for i in range(2, xls_table.nrows):
                user_row = xls_table.row_values(i)
                team_id = user_row[0]
                if team_id[0:4] != 'team':
                    continue
                team = AccountModel.User.objects.filter(id=team_id)
                if not team.exists():
                    continue
                team = team[0]
                team.nickname = user_row[1]
                team.realname = user_row[2]
                team.sex = 0 if str(user_row[3]) == 'Y' else 1
                team.password = self._user_session.gen_passwd(user_row[4])
                team.locked = False
                team.save()
            self._result = kernel.RESTStruct(True)
        except:
            self._result = kernel.RESTStruct(False, "XLS文件处理过程出现错误，请检查XLS文件是否填写正确")
            return

    def mgr_reset_user_passwd(self, contest_id):
        """
        重设专用账户的密码
        :param contest_id:
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != 'acm':
            self._result = kernel.RESTStruct(False, "只有ACM协会专用账号才能够执行该操作")
            return

        uid = self._request.POST.get('user_id', '')
        pwd = self._request.POST.get('pwd', '')

        if uid.strip() == '' or uid[0:4] != 'team':
            self._result = kernel.RESTStruct(False, "仅支持修改比赛专用账户的密码")
            return

        if pwd.strip() == '':
           pwd = "123456"

        team = AccountModel.User.objects.filter(id=uid)
        if not team.exists():
            self._result = kernel.RESTStruct(False, "未找到比赛专用账户")
            return
        team = team[0]
        team.password = self._user_session.gen_passwd(pwd)
        team.save()
        self._result = kernel.RESTStruct(True)

    def mgr_lock_contest_user(self, contest_id):
        """
        锁定/解锁专用账户
        :param contest_id:
        :return:
        """
        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return

        if self._user_session.user_id != 'acm':
            self._result = kernel.RESTStruct(False, "只有ACM协会专用账号才能够执行该操作")
            return

        action = self._request.GET.get('action', '')
        uid = self._request.GET.get('user_id', '')
        if uid.strip() == '' or uid[0:4] != 'team':
            self._result = kernel.RESTStruct(False, "仅支持修改比赛专用账户的密码")
            return

        team = AccountModel.User.objects.filter(id=uid)
        if not team.exists():
            self._result = kernel.RESTStruct(False, "未找到比赛专用账户")
            return
        team = team[0]
        team.locked = True if action == 'lock' else False
        team.save()
        self._result = kernel.RESTStruct(True)

    def mgr_code_export(self, contest_id):

        self._action = kernel.const.VIEW_ACTION_JSON

        if not self._check_login(True):
            return

        contest = self._get_contest(contest_id)
        if contest is None:
            self._send_error_contest_doesnt_exists(True)
            return

        if not self._check_permission(contest):
            self._send_error_contest_permission_denied(True)
            return
        # 获取题目数据
        cproblem_list = contest.problemset.order_by("index")
        # 题目索引参照表
        cpindex_list = {}
        for cproblem in cproblem_list:
            cpindex_list[cproblem.problem.id] = cproblem.index
        # 初始化Storage
        status_storage = kernel.LocalStorage(kernel.const.USER_UPLOADCODE_DIR, "")
        filename = "%s.zip" % uuid.uuid1()
        filepath = "%s/%s/%s" % (kernel.const.EXPORT_PROCESS_TEMP_DIR, 'contest_ce', filename)
        zf = zipfile.ZipFile(filepath, "w", zipfile.zlib.DEFLATED)
        # 遍历所有符合条件的status
        judge_status = contest.judge_status.filter(flag=0)
        for status in judge_status:
            stor_name = u"%s_%s_%s.%s" % (
                status.author.id,
                cpindex_list.get(status.problem.id, status.problem.id),
                status.id,
                kernel.const.SOURCE_CODE_EXTENSION.get(status.lang)
            )
            upload_code = status_storage.get_file_path(status.code_path)
            zf.write(upload_code, stor_name)
        zf.close()
        self._result = kernel.RESTStruct(True, data="/resource/export_temp/contest_ce/%s" % filename)
